#!/usr/bin/env python3
"""
Advanced usage example for GSI Wiki Generator
"""

import json
from pathlib import Path
from gsi_wiki_generator import GSIWikiGenerator, WikiConfig


def create_custom_config():
    """Create a custom configuration for specific needs"""
    
    config = WikiConfig(
        input_directory="/home/docker/comgsi/tutorial/comGSIv3.7_EnKFv1.3/src/comGSI-wiki",
        output_directory="./advanced_output",
        outline_file="gsi_drp4dvar_wiki_outline.json",
        max_results=20,  # More comprehensive search
        min_score=0.15,  # Lower threshold for more results
        claude_timeout=180,  # Longer timeout for complex questions
        search_timeout=90,   # Longer search timeout
        enable_cache=True
    )
    
    # Save configuration for reuse
    config.save_to_file("advanced_config.json")
    return config


def monitor_progress(generator):
    """Monitor generation progress with detailed reporting"""
    
    progress = generator.get_progress_report()
    
    print("=== Progress Report ===")
    print(f"Input Directory: {progress['input_directory']}")
    print(f"Session ID: {progress['session_id']}")
    print(f"Last Updated: {progress['last_updated'] or 'Not started'}")
    print()
    
    print("Search Progress:")
    print(f"  Completed: {progress['completed_searches']}/{progress['total_searches']}")
    print(f"  Percentage: {progress['search_progress_percent']:.1f}%")
    print(f"  Remaining: {progress['remaining_searches']}")
    print()
    
    print("Question Answering Progress:")
    print(f"  Completed: {progress['completed_questions']}/{progress['total_questions']}")
    print(f"  Percentage: {progress['question_progress_percent']:.1f}%")
    print(f"  Remaining: {progress['remaining_questions']}")
    print()


def inspect_cached_results(generator):
    """Inspect cached search results and answers"""
    
    # Check if cache files exist
    cache_file = generator.progress_cache_file
    if cache_file.exists():
        with open(cache_file, 'r', encoding='utf-8') as f:
            cache_data = json.load(f)
        
        print("=== Cache Inspection ===")
        print(f"Cache file: {cache_file}")
        print(f"Completed searches: {len(cache_data.get('completed_searches', []))}")
        print(f"Completed questions: {len(cache_data.get('completed_questions', []))}")
        print(f"Cache size: {cache_file.stat().st_size / 1024:.1f} KB")
        
        # Show sample cached searches
        if cache_data.get('completed_searches'):
            print("\nSample completed searches:")
            for search in cache_data['completed_searches'][:3]:
                print(f"  - {search}")
        
        # Show sample cached questions
        if cache_data.get('completed_questions'):
            print("\nSample completed questions:")
            for question in cache_data['completed_questions'][:2]:
                print(f"  - {question[:60]}...")
    else:
        print("No cache file found")


def incremental_generation(config):
    """Demonstrate incremental generation with pause/resume capability"""
    
    print("=== Incremental Generation Demo ===")
    
    generator = GSIWikiGenerator(config)
    
    print("Initial state:")
    monitor_progress(generator)
    
    try:
        # In a real scenario, you might want to interrupt after some searches
        # This demonstrates that the generator can be stopped and resumed
        
        print("\nStarting wiki generation...")
        print("(In production, you can interrupt with Ctrl+C and resume later)")
        
        wiki_file = generator.save_wiki("incremental_wiki.md")
        
        print(f"\nGeneration completed!")
        print(f"Wiki saved to: {wiki_file}")
        
        print("\nFinal state:")
        monitor_progress(generator)
        
    except KeyboardInterrupt:
        print("\nGeneration interrupted!")
        print("Progress has been saved. You can resume by running the same command again.")
        monitor_progress(generator)


def custom_search_analysis(generator):
    """Analyze search results for quality assessment"""
    
    search_results_file = generator.search_cache_file
    
    if search_results_file.exists():
        with open(search_results_file, 'r', encoding='utf-8') as f:
            search_data = json.load(f)
        
        print("=== Search Results Analysis ===")
        print(f"Total search queries: {len(search_data)}")
        
        # Analyze result quality
        total_results = 0
        high_score_results = 0
        
        for query, results in search_data.items():
            if results:
                for result in results:
                    if 'parsed_results' in result:
                        for parsed in result['parsed_results']:
                            total_results += 1
                            if parsed.get('score', 0) > 0.5:
                                high_score_results += 1
        
        print(f"Total code snippets found: {total_results}")
        print(f"High-quality results (score > 0.5): {high_score_results}")
        print(f"Quality ratio: {high_score_results/total_results*100:.1f}%" if total_results > 0 else "No results")
        
        # Show top queries by result count
        query_counts = {}
        for query, results in search_data.items():
            if results and 'parsed_results' in results[0]:
                query_counts[query] = len(results[0]['parsed_results'])
        
        if query_counts:
            print("\nTop 5 queries by result count:")
            top_queries = sorted(query_counts.items(), key=lambda x: x[1], reverse=True)[:5]
            for query, count in top_queries:
                print(f"  {count} results: {query}")


def main():
    """Advanced usage demonstration"""
    
    print("🚀 GSI Wiki Generator - Advanced Usage Demo\n")
    
    # Create custom configuration
    config = create_custom_config()
    print(f"Created custom configuration: advanced_config.json")
    
    # Initialize generator
    generator = GSIWikiGenerator(config)
    
    # Monitor initial progress
    monitor_progress(generator)
    
    # Inspect any existing cache
    inspect_cached_results(generator)
    
    # Analyze search results if available
    custom_search_analysis(generator)
    
    # Demonstrate incremental generation
    # incremental_generation(config)  # Uncomment to run full generation
    
    print("\n✅ Advanced usage demo completed!")
    print("\nTo run full generation, uncomment the incremental_generation() call")
    print("or use the CLI: gsi-wiki-gen --config advanced_config.json")


if __name__ == "__main__":
    main()